import styles from './index.module.less'
import cm from 'classnames'
import { getNeedPassed } from '@/api/admin'
import { useSetState } from 'ahooks'
import { useEffect, useMemo, useState,useRef } from 'react'
import { timestampToYmd,isElementInViewport } from '@/utils/utils'
import { EXAMINE_ENUM, VALID_ROLE_TYPE } from '@/constant'
import Sure from './components/sure'
import Reject from './components/reject'
import Loading from '@/components/fetch-loading'
import { debounce } from 'lodash-es'

const Index = () => {
  const scrollRef = useRef(null)
  const [pageData, setPageData] = useSetState({
    page: 1,
    pageSize: 30,
    listLoading: true,
    list:[],
    currentUserIndex:0,
    sure:false,
    reject:false,
    init:false
  })
  const [pageNo, setPageNo] = useState(1)
  const currentUser = useMemo(() => {
    if (!pageData.list.length) {
      return {}
    }
    return pageData.list[pageData.currentUserIndex]
  }, [pageData.currentUserIndex, pageData.list])



  const closePanel = () => {
    setPageData({ sure: false, reject: false })
  }


  useEffect(() => {
    setPageData({init:true})
    const scrollListen = debounce(handleScroll, 500)
    scrollRef.current.addEventListener('scroll', scrollListen)
    
    return () => {
      scrollRef?.current?.removeEventListener('scroll', scrollListen)
    }
  }, [])

  const handleScroll = () => {
    if (isElementInViewport(scrollRef.current)) {
      setPageNo(page => page + 1)
    }
  }

    // page变化，加载数据
    useEffect(() => {
      if(!pageData.init){
        setPageData({isLoading:true})
        getNeedPassed({ page: 1, pageSize: pageData.pageSize }).then((res) => {
          if (!res.code) {
            const data = res.data.list || []
            setPageData({ list:data,isEnd:data.length < pageData.pageSize,isLoading:false })
          }
        })
        return
      }
      if (pageData.isEnd) return
      setPageData({isLoading:true})
      getNeedPassed({ page: pageNo, pageSize: pageData.pageSize }).then((res) => {
        if (!res.code) {
          const data = res.data.list || []
          setPageData({ isLoading:false,list:[...pageData.list,...data],isEnd:data.length < pageData.pageSize })
        }
      })
    }, [pageNo])

  return (
    <div className={styles.home}>
      {pageData.isLoading && (
        <Loading className="w-full h-full absolute left-0 top-0 flex items-center justify-center " />
      )}
      <div className={cm(styles.left, 'beautifyScroll')} ref={scrollRef}>
        {pageData.list.map((item, index) => {
          const statusText = EXAMINE_ENUM[item.status]
          return (
            <div
              className={cm(styles.leftItem, index === pageData.currentUserIndex ? styles.active : '')}
              key={item.id}
              onClick={() => setPageData({currentUserIndex:index})}
            >
              <div className={styles.avator}>
                <img src="/images/partner.webp" />
                {item.status === 1 && <span className={styles.point}></span>}
              </div>
              <div className={styles.email}>
                <p className="textEllipsis">{item.user.email}</p>
                <p className="textEllipsis">{timestampToYmd(item.applyTime * 1000)}</p>
              </div>
              <div
                className={cm(styles.btn, {
                  [styles.btn2]: item.status === 2,
                  [styles.btn3]: item.status === 3,
                })}
              >
                {statusText}
              </div>
            </div>
          )
        })}
      </div>
      <div className={cm(styles.right, 'beautifyScroll')}>
        <div className={styles.header}>
          <img className={styles.avator} src="/images/partner.webp" />
          <div className={styles.email}>
            <p className="textEllipsis">{currentUser.user?.email}</p>
            <p className="textEllipsis">申请角色：{currentUser.actor?.name}</p>
          </div>
          {currentUser.status !== VALID_ROLE_TYPE && (
            <div className={styles.btnGroup}>
              <div className={styles.btn} onClick={() => setPageData({ sure: true, reject: false })}>
                通过
              </div>
              <div
                className={cm(styles.btn, styles.btnReject)}
                onClick={() => setPageData({ reject: true, sure: false })}
              >
                拒绝
              </div>
              {pageData.sure && (
                <Sure refresh={fetchData} id={currentUser.id} close={closePanel} className={styles.showPanel} />
              )}
              {pageData.reject && (
                <Reject refresh={fetchData} id={currentUser.id} close={closePanel} className={styles.showPanel} />
              )}
            </div>
          )}
        </div>
        <hr className={styles.hrSpace} />
        <p className={styles.label}>联系方式</p>
        <div className={styles.textBox}>
          <div className="textEllipsis">Whatsapp：{currentUser.user?.whatsapp}</div>
          <div className="textEllipsis">Telegram：{currentUser.user?.telegram}</div>
          <div className="textEllipsis">微信：{currentUser.user?.wechat}</div>
        </div>
        <p className={styles.label}>您是通过什么方式进行营销的？</p>
        <div className={styles.text}>{currentUser.marketingModes?.join('、')}</div>
        <p className={styles.label}>请列出您的所选营销方式的网址</p>
        <div className={styles.text}>{currentUser.marketingSites}</div>
        <p className={styles.label}>请简要描述您的流量类型</p>
        <div className={styles.text}>{currentUser.flowDesc}</div>
      </div>
    </div>
  )
}

export default Index
